<template>
  <div class="yy-page yy-base-category">

    <div class="yy-page-search" v-if="showSearch">
      <WidgetForm ref="searchFormWidget" :option="{
        style: 'display: flex;',
        itemStyle: 'margin-right: 10px;margin-bottom: 0;align-items: center;'
      }" :form-fields="search.formFields" :form-buttons="search.formButtons" />
    </div>

    <div class="yy-page-header">

      <div class="yy-page-header_title">
        <el-button  color="#009688" @click="onOpenDialog()">新增设备</el-button>
      </div>
      <div class="yy-page-header_action">
        <right-toolbar @showSearch="onShowSearch" @queryTable="getDeviceList"></right-toolbar>
      </div>
    </div>
    <div class="yy-page-data" style="flex:1; min-height: 0;">
       <WidgetTable ref="tableDataRef" :is-loading="table.isLoading" :columns="table.columns" :data="table.data" :formats="table.formats" :paging-data="table.paging"></WidgetTable>
    </div>
    <WidgetFormDialog ref="widgetFormDialogRef"
                      :form-fields="dialog.formFields"
                      :model-instance="dialog.modelInstance"
                      :save-api-fun="dialog.saveApiFun"
                      :update-api-fun="dialog.updateApiFun"
                      :option="{
                      businessName: '设备',
                      formLabelWidth: '80px'
                    }"
                      @edit-callback="onEditCallback"
    />
    <BroadcastSettingDialog ref="broadcastSettingDialogRef" @operator-callback="onOperatorCallback"/>
  </div>
</template>

<script setup lang="ts">

import {nextTick, onBeforeMount, reactive, ref} from "vue";
import {TableColumn, WidgetFormField} from "@/model/Definition";
import {BaseModel} from "@/model/BaseModel";
import {formatDate} from "@/utils/yayi";
import {ElButton, ElMessage} from "element-plus";
import {DeviceModel, UsedTypeEnum} from "@/model/DeviceModel";
import DeviceApi from "@/api/queue/DeviceApi";
import {useRouter} from "vue-router";
import WidgetTable from "@/components/widget/WidgetTable.vue";
import WidgetFormDialog from "@/components/widget/WidgetFormDialog.vue";
import DeviceConfig from "@/views/queue/device/DeviceConfig.vue";
import useDeviceCategoryStore from "@/store/modules/device_category"
import BroadcastSettingDialog from "@/views/queue/device/BroadcastSettingDialog.vue";
import WidgetForm from "@/components/widget/WidgetForm.vue";
import {EmployeeModel} from "@/model/EmployeeModel";
import EmployeeApi from "@/api/system/empl";
import DepartSelector from "@/components/Business/DepartSelector.vue";
import useUserStore from "@/store/modules/user";

const showSearch = ref(true)
const router = useRouter()
const userStore = useUserStore()
const search = reactive<{formFields: WidgetFormField[],formData: any, formButtons: any, modelInstance: BaseModel, searchApiFun:any}>({
  modelInstance: new EmployeeModel(),
  searchApiFun: EmployeeApi.listEmployee,
  formData: {
    deptId: userStore.deptId || null,
  },
  formFields: [
    {field: 'deptId', initVal: () => userStore.deptId || null,  config: {select: {clearable: true}},
      placeholder:'请选择科室', label: '所属科室', type: 'templateField', style:'width: 150px;', component: DepartSelector,
      atChange: ({deptId, depart}) => {
        search.formData.deptId = deptId
        getDeviceList()
      }
    },
    {field: 'searchKey', config: {input: {clearable: true}}, placeholder:'名称或代码关键字', label: '关键字', type: 'text', style:'width: 150px;',
      atChange: (searchKey) => {
        search.formData.searchKey = searchKey
        getDeviceList()
      }
    },
  ],
  formButtons: []
})
const dialog = reactive<{formFields: WidgetFormField[],modelInstance: BaseModel, saveApiFun: any, updateApiFun: any}>({
  modelInstance: new DeviceModel(),
  saveApiFun: DeviceApi.saveDevice,
  updateApiFun: DeviceApi.updateDevice,
  formFields: [
    {field: 'name', label: '名称', type: 'text', placeholder: '请输入名称', required: [{required: true, message: '设备名称不能为空', trigger: 'blur'}]},
    {field: 'code', label: 'IP', type: 'text', placeholder: '请输入代码', required: [{required: true, message: '设备代码不能为空', trigger: 'blur'}],
      atChange: (val, row) => {
        const field = dialog.formFields.find(item => item.field === 'ip')
        field.initVal = val
        widgetFormDialogRef.value.setFieldValue("ip", val)
      }
    },
    {field: 'ip', hide: true, label: 'IP', type: 'text', placeholder: '请输入IP'},
    {field: 'location', label: '设备位置', type: 'text', placeholder: '请输入设备位置'},
    { field: 'usedType', initVal: 6, label: '设备分类', type: 'select',
      config: {
        select: {clearable: false}
      },
      placeholder: '请选择分类',
      options: DeviceModel.UsedTypeArr,
      atChange: (val, row) => {
        if (val === UsedTypeEnum.INFORMATION_PUBLISH) {
          const field = dialog.formFields.find(item => item.field === 'config')
          field.hide = true
        } else {
          const field = dialog.formFields.find(item => item.field === 'config')
          field.hide = false
          widgetFormDialogRef.value.showOrHideField('relateItem', [UsedTypeEnum.APPLE_NO_CLIENT].indexOf(val) == -1)
          widgetFormDialogRef.value.showOrHideField('itemIds', [UsedTypeEnum.NURSE_CLIENT, UsedTypeEnum.CALL_SCREEN].indexOf(val) == -1)
          widgetFormDialogRef.value.showOrHideField('deptIds', [UsedTypeEnum.SIGN_SCREEN].indexOf(val) == -1)
        }
      }
    },
    {field: 'config', hide: false, label: '设备配置', type: 'template', component: DeviceConfig},
    {field: 'heartbeat', label: '心跳', initVal: 60, type: 'number', placeholder: '请输入心跳', hide: true},
    {field: 'keywords', label: '检索码', type: 'text', placeholder: '请输入检索码',hide: true},
    {field: 'deptId', initVal: () => search.formData.deptId, hide: true, label: '所属科室', type: 'templateField', component: DepartSelector},
    {field: 'state', label: '状态', type: 'radioGroup', initVal: 1, options: [{label: '启用', value: 1}, {label: '停用', value: 0}]}
  ]
})

const table = reactive<{
  isLoading: boolean,
  paging: any,
  columns: TableColumn[],
  data: DeviceModel[],
  formats?: any
}>({
  isLoading: false,
  columns: [
    {
      "field":"index",
      "label":"序号",
      "type": "index",
      "showable":true,
      "align": 'center',
      "width": 60,
      "fixed": 'left'
    },
    {
      "field":"name",
      "label":"名称",
      "showable":true,
      "fixed": 'left'
    },
    {
      "field":"code",
      "label":"代码",
      "showable":true
    },
    {
      "field":"ip",
      "label":"IP",
      "showable":true
    },
    {
      "field":"usedType",
      "label":"设备分类",
      "showable":false
    },
    {
      "field":"location",
      "label":"位置",
      "showable":true
    },
    {
      "field":"lastConnectTime",
      "label":"上一次连接时间",
      "showable":true
    },
    {
      "field":"deptName",
      "label":"科室",
      "showable":true
    },
    {
      "field":"updateBy",
      "label":"更新用户",
      "showable":true,
      "width": 120
    },
    {
      "field":"updateTime",
      "label":"更新时间",
      "showable":true,
      "width": 140
    },
    {
      "field":"state",
      "label":"状态",
      "showable":true,
      "width": 80,
      "fixed": 'right',
      "align": 'center'
    },
    {
      "field":"action",
      "label":"操作",
      "width": 190,
      "showable":true,
      "fixed": 'right'
    }
  ],
  paging: {
    isPaging: true,
    total: 0,
    pageIndex: 1,
    pageSize: 30,
    pageChange: (pageIndex: number) => {
      if (pageIndex != table.paging.pageIndex) {
        getDeviceList(pageIndex);
      }
    }
  },
  data: [],
  formats: {
    'usedType': {
      labelFormat: (val, row) => DeviceModel.UsedTypeArr.find(item => item.value === val)?.label
    },
    'categoryId': {
      labelFormat: (val, row) => deviceCategoryList.value.find(item => item.id === val)?.name
    },
    'state': {
      textType:'text',
      typeFormat: DeviceModel.getStateType,
      labelFormat: DeviceModel.getStateLabel
    },
    'lastConnectTime': {
      labelFormat: (val) =>formatDate(val)
    },
    'updateTime': {
      labelFormat: (val) =>formatDate(val)
    },
    'action': {
      items: [
        {label: '插播', elType: 'button', value: 'edit', atClick: (device: DeviceModel) =>
          {
            broadcastSettingDialogRef.value.onShowDialog(device)
          }
        },
        {label: '编辑', elType: 'button', value: 'edit', atClick: (device: DeviceModel) => onOpenDialog(device)},
        {label: '删除', elType: 'button', value: 'delete',  confirm: {title: '您确定要删除改类目吗？', atConfirm: (device: DeviceModel) => onDeleteCategory(device)}}
      ]
    }
  }
})
const searchFormWidget = ref()
const widgetFormDialogRef = ref()
const selectUsedType = ref(0)
const broadcastSettingDialogRef = ref()
const tableDataRef = ref()

const deviceCategoryList = ref([])

onBeforeMount(() => {
  getDeviceList()
})
const onShowSearch = () => {
  showSearch.value = !showSearch.value
  tableDataRef.value.onWindowResize()
}
const getDeviceList = (pageIndex = 1) => {
  table.isLoading = true
  DeviceApi.listDevice(search.formData.searchKey, search.formData.deptId, search.formData.usedType,  pageIndex, table.paging.pageSize).then((res) => {
    table.paging = Object.assign({}, table.paging, {pageIndex: res.pageIndex, total: res.total})
    table.data = res.data
    table.isLoading = false
  }, () => {
    table.isLoading = false
  })
}

const onSelectUsedType = () => {
  getDeviceList()
}

const onOpenDialog = (device?: DeviceModel) => {
  if (device) {
    const field = dialog.formFields.find(item => item.field === 'usedType')
    field.initVal = device.usedType
    field.atChange(field.initVal, field)
  }
  widgetFormDialogRef.value.onShowDialog(device)
}

const onDeleteCategory = (device: DeviceModel) => {
  DeviceApi.deleteDevice(device.id).then(() => {
    const index = table.data.findIndex(item => item.id === device.id);
    table.data.splice(index, 1)
    ElMessage.success({
      message: '设备删除成功',
      showClose: true
    })
  })
}

const onOperatorCallback = () => {

}

const onEditCallback = (device: DeviceModel) => {
  const index = table.data.findIndex(item => item.id === device.id);
  if (index < 0) {
    table.data.unshift(device)
  } else {
    table.data.splice(index, 1, device)
  }
}
</script>

<style scoped lang="scss">
.yy-base-category {
  height: 100%;
}
</style>
